package com.hongxun.net;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.budget.ui.activity.sg.ConstructionTwoActivity;
import com.hongxun.budget.utils.BitmapUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.SgDBUtils;
import com.hongxun.budget.utils.SgStrKey;
import com.hongxun.budget.utils.ZipUtils;
import com.hongxun.greenentity.sg.CArrivalRecordEntity;
import com.hongxun.greenentity.sg.CBasicsWorkEntity;
import com.hongxun.greenentity.sg.CGoodsDetailEntity;
import com.hongxun.greenentity.sg.CGroundEntity;
import com.hongxun.greenentity.sg.CLinePitEntity;
import com.hongxun.greenentity.sg.CMiddleCheckEntity;
import com.hongxun.greenentity.sg.CPolePitEntity;
import com.hongxun.greenentity.sg.CScheduleEntity;
import com.hongxun.greenentity.sg.CScheduleReportEntity;
import com.hongxun.greenentity.sg.CStackPointEntity;
import com.hongxun.greenentity.tk.DPictureEntity;
import com.hongxun.interfaces.NovaCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by admin on 2018/8/31.
 */

public class SgProjectNet extends BaseNet {

    //----------------new----------------//

    public static List<DPictureEntity> photos = new ArrayList<>();
    public static List<DPictureEntity> photosAll = new ArrayList<>();

    //判断项目是否删除或归档
    public static void getProjectState(Context context, NovaCallback callback, int calli) {
        getDialog(context, "项目状态获取中...");
        String uuid = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
        Map<String, Object> map = getParams(context);
        map.put("pGuid", uuid);//项目ID
        getNovate(context).rxPost(Contants.getProjectState, map, new Callback(calli, callback, d));
    }

    /**
     * 提交项目进度数据
     *
     * @param context
     * @param callback
     * @param calli
     */
    public static void upProjectProgress(final Context context, final NovaCallback callback, final int calli) {
        getDialog(context, "项目进度上传中...");
        String uuid = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
        Observable.just(uuid).subscribeOn(Schedulers.io()).map(new Func1<String, Map<String, Object>>() {
            @Override
            public Map<String, Object> call(String uuid) {
                photos.clear();
                photosAll.clear();
                List<CScheduleEntity> cScheduleList = new ArrayList<>();
                List<CScheduleReportEntity> cScheduleReportList = new ArrayList<>();
                for (CScheduleEntity entity : SgDBUtils.getScheduleCj(uuid)) {
                    if (!entity.getSDatastate().equals(SgStrKey.ytb)) {
                        cScheduleList.add(entity);
                    }
                    for (CScheduleReportEntity reportEntity : SgDBUtils.getScheduleReportAll(entity.getGuid())) {
                        if (!reportEntity.getSRDatastate().equals(SgStrKey.ytb)) {
                            cScheduleReportList.add(reportEntity);
                        }
                        for (DPictureEntity pictureEntity : SgDBUtils.getPictureAll(reportEntity.getGuid())) {
                            photosAll.add(pictureEntity);
                            if (!pictureEntity.getPDatastate().equals(SgStrKey.ytb)) {
                                photos.add(pictureEntity);
                            }
                        }
                    }
                }
                Map<String, Object> map = getParams(context);
                map.put("pGuid", uuid);//项目ID
                map.put("cScheduleList", JSON.toJSONString(cScheduleList));//进度记录
                map.put("cScheduleReportList", JSON.toJSONString(cScheduleReportList));//填报记录
                return map;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Map<String, Object>>() {
            @Override
            public void call(Map<String, Object> map) {
                getNovate(context).rxPost(Contants.ProjectProgress, map, new Callback(calli, callback, d));
            }
        });
    }

    /**
     * 获取项目进度数据
     */
    public static void getProjectProgress(Context context, NovaCallback callback, int calli) {
        getDialog(context, "项目进度下载中...");
        String uuid = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
        Map<String, Object> map = getParams(context);
        map.put("pGuid", uuid);//项目ID
        map.put("type", 1);//项目进度
        getNovate(context).rxPost(Contants.getProjectProgress, map, new Callback(calli, callback, d));
    }

    /**
     * 提交材料到场数据
     *
     * @param context
     * @param callback
     * @param calli
     */
    public static void upProjectPresent(final Context context, final NovaCallback callback, final int calli) {
        getDialog(context, "材料到场上传中...");
        String uuid = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
        Observable.just(uuid).subscribeOn(Schedulers.io()).map(new Func1<String, Map<String, Object>>() {
            @Override
            public Map<String, Object> call(String uuid) {
                photos.clear();
                photosAll.clear();
                List<CStackPointEntity> wzPoint = new ArrayList<>();
                List<CArrivalRecordEntity> dhRecord = new ArrayList<>();
                List<CGoodsDetailEntity> wzMaterial = new ArrayList<>();
                for (CStackPointEntity entity : SgDBUtils.getStackPointAll(uuid)) {
                    if (!entity.getSPDatastate().equals(SgStrKey.ytb)) {
                        wzPoint.add(entity);
                    }
                    for (CArrivalRecordEntity recordEntity : SgDBUtils.getArrivalRecordAll(entity.getGuid())) {
                        if (!recordEntity.getARDatastate().equals(SgStrKey.ytb)) {
                            dhRecord.add(recordEntity);
                        }
                        wzMaterial.addAll(SgDBUtils.getGoodsDetailAll(recordEntity.getGuid()));
                        for (DPictureEntity pictureEntity : SgDBUtils.getPictureAll(recordEntity.getGuid())) {
                            photosAll.add(pictureEntity);
                            if (!pictureEntity.getPDatastate().equals(SgStrKey.ytb)) {
                                photos.add(pictureEntity);
                            }
                        }
                    }
                }
                Map<String, Object> map = getParams(context);
                map.put("pGuid", uuid);//项目ID
                map.put("cArrivalRecordEntityList", JSON.toJSONString(dhRecord));//到货记录
                map.put("cStackPointEntityList", JSON.toJSONString(wzPoint));//物资堆放点
                map.put("cGoodsDetailEntityList", JSON.toJSONString(wzMaterial));//到货物资
                return map;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Map<String, Object>>() {
            @Override
            public void call(Map<String, Object> map) {
                getNovate(context).rxPost(Contants.ProjectPresent, map, new Callback(calli, callback, d));
            }
        });
    }

    /**
     * 获取材料到场数据
     */
    public static void getProjectPresent(Context context, NovaCallback callback, int calli) {
        getDialog(context, "材料到场下载中...");
        String uuid = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
        Map<String, Object> map = getParams(context);
        map.put("pGuid", uuid);//项目ID
        map.put("type", 2);//材料到场
        getNovate(context).rxPost(Contants.getProjectPresent, map, new Callback(calli, callback, d));
    }

    /**
     * 提交中间检查数据
     *
     * @param context
     * @param callback
     * @param calli
     */
    public static void upProjectMiddleCheck(final Context context, final NovaCallback callback, final int calli) {
        getDialog(context, "中间检查上传中...");
        String uuid = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
        Observable.just(uuid).subscribeOn(Schedulers.io()).map(new Func1<String, Map<String, Object>>() {
            @Override
            public Map<String, Object> call(String uuid) {
                photos.clear();
                photosAll.clear();
                List<CMiddleCheckEntity> zjRecord = new ArrayList<>();
                List<CPolePitEntity> listinfo1 = new ArrayList<>();
                List<CLinePitEntity> listinfo2 = new ArrayList<>();
                List<CGroundEntity> listinfo3 = new ArrayList<>();
                List<CBasicsWorkEntity> listinfo4 = new ArrayList<>();
                for (CMiddleCheckEntity entity : SgDBUtils.getMiddleCheckAll(uuid)) {
                    if (!entity.getMCDatastate().equals(SgStrKey.ytb)) {
                        zjRecord.add(entity);
                    }
                    for (CPolePitEntity polePitEntity : SgDBUtils.getPolePitAll(entity.getGuid())) {
                        if (!polePitEntity.getPPDatastate().equals(SgStrKey.ytb)) {
                            listinfo1.add(polePitEntity);
                        }
                        List<DPictureEntity> pictureAll = SgDBUtils.getPictureAll(polePitEntity.getGuid());
                        for (DPictureEntity pictureEntity : pictureAll) {
                            photosAll.add(pictureEntity);
                            if (!pictureEntity.getPDatastate().equals(SgStrKey.ytb)) {
                                photos.add(pictureEntity);
                            }
                        }
                    }
                    for (CLinePitEntity linePitEntity : SgDBUtils.getLinePitAll(entity.getGuid())) {
                        if (!linePitEntity.getLPDatastate().equals(SgStrKey.ytb)) {
                            listinfo2.add(linePitEntity);
                        }
                        List<DPictureEntity> pictureAll = SgDBUtils.getPictureAll(linePitEntity.getGuid());
                        for (DPictureEntity pictureEntity : pictureAll) {
                            photosAll.add(pictureEntity);
                            if (!pictureEntity.getPDatastate().equals(SgStrKey.ytb)) {
                                photos.add(pictureEntity);
                            }
                        }
                    }
                    for (CGroundEntity groundEntity : SgDBUtils.getGroundAll(entity.getGuid())) {
                        if (!groundEntity.getGDatastate().equals(SgStrKey.ytb)) {
                            listinfo3.add(groundEntity);
                        }
                        List<DPictureEntity> pictureAll = SgDBUtils.getPictureAll(groundEntity.getGuid());
                        for (DPictureEntity pictureEntity : pictureAll) {
                            photosAll.add(pictureEntity);
                            if (!pictureEntity.getPDatastate().equals(SgStrKey.ytb)) {
                                photos.add(pictureEntity);
                            }
                        }
                    }
                    for (CBasicsWorkEntity workEntity : SgDBUtils.getBasicsWorkAll(entity.getGuid())) {
                        if (!workEntity.getBWDatastate().equals(SgStrKey.ytb)) {
                            listinfo4.add(workEntity);
                        }
                        List<DPictureEntity> pictureAll = SgDBUtils.getPictureAll(workEntity.getGuid());
                        for (DPictureEntity pictureEntity : pictureAll) {
                            photosAll.add(pictureEntity);
                            if (!pictureEntity.getPDatastate().equals(SgStrKey.ytb)) {
                                photos.add(pictureEntity);
                            }
                        }
                    }
                }
                Map<String, Object> map = getParams(context);
                map.put("pGuid", uuid);//项目ID
                map.put("cMiddleCheckEntityList", JSON.toJSONString(zjRecord));//中间检查记录
                map.put("cPolePitEntityList", JSON.toJSONString(listinfo1));//杆塔坑
                map.put("cLinePitEntityList", JSON.toJSONString(listinfo2));//拉线坑
                map.put("cGroundEntityList", JSON.toJSONString(listinfo3));//接地体
                map.put("cBasicsWorkEntityList", JSON.toJSONString(listinfo4));//设备基础
                return map;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Map<String, Object>>() {
            @Override
            public void call(Map<String, Object> map) {
                getNovate(context).rxPost(Contants.ProjectMiddleCheck, map, new Callback(calli, callback, d));
            }
        });

    }

    /**
     * 获取中间检查数据
     */
    public static void getProjectMiddleCheck(Context context, NovaCallback callback, int calli) {
        getDialog(context, "中间检查下载中...");
        String uuid = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
        Map<String, Object> map = getParams(context);
        map.put("pGuid", uuid);//项目ID
        map.put("type", 3);//中间检查
        getNovate(context).rxPost(Contants.getProjectMiddleCheck, map, new Callback(calli, callback, d));
    }


    public static void upPhotoSg(final Context context, final NovaCallback callback, int calli) {
        if (photos.isEmpty()) {
            d.cancel();
            callback.success(calli, null);
            return;
        }
        List<DPictureEntity> upList = new ArrayList<>();//10张图片提交一次
        List<DPictureEntity> upList2 = new ArrayList<>();//10张图片提交一次
        for (int j = 0; j < photos.size(); j++) {
            DPictureEntity d = photos.get(j);
            upList2.add(d);
            //照片先压缩一次
            boolean isNew = d.getPDatastate().equals(SgStrKey.add);
            if (isNew) {
                String path = d.getPAppaddress();
                File file = BitmapUtils.saveToCache(context,BitmapUtils.decodeSampledSize(path, 400, 800));
                path = file.getPath();
                if (d.getPPResour().equals("相机")) {
                    new File(d.getPAppaddress()).delete();
                }
                d.setPAppaddress(path);
                d.setPName(path.substring(path.lastIndexOf("/") + 1));
            }
            upList.add(d);
            if (j == 9) break;
        }
        photos.removeAll(upList2);//移除已提交图片数据
        ZipUtils.zip(upList);//打包图片文件
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data; charset=utf-8"), new File(ZipUtils.zipFilePath));
//        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), new File(ZipUtils.zipFilePath));
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("fileName", "zip", requestFile)
                .addFormDataPart("photo", JSON.toJSONString(upList))
                .build();
        //photoUpload/ProjectSgImg
        getNovate(context).rxUploadWithBody(System.currentTimeMillis(), Contants.ProjectSgImg, requestBody,
                new Callback(calli, new NovaCallback() {
                    @Override
                    public void success(int i, JSONObject obj) {
                        if (photos.isEmpty()) {
                            d.cancel();
                            callback.success(i, null);
                        } else {
                            upPhotoSg(context, callback, i);
                        }
                    }

                    @Override
                    public void err(int i, int status, String err) {
                        d.cancel();
                        callback.err(i, status, err);
                    }
                }, null));
    }

    /**
     * 提交施工项目照片
     *
     * @param context
     * @param callback
     * @param calli
     */
    public static void upPhotoSgAllPart(Context context, NovaCallback callback, int calli) {
        getDialog(context, "图片上传中...");
        upPhotoSg(context, callback, calli);
    }

    /**
     * 获取项目照片数据
     */
    public static void getPhotoSg(Context context, NovaCallback callback, int calli, int type) {
        getDialog(context, "照片数据下载中...");
        String uuid = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
        Map<String, Object> map = getParams(context);
        map.put("pGuid", uuid);//项目ID
        map.put("photoType", type);//照片类别
        getNovate(context).rxPost(Contants.getProjectSgImg, map, new Callback(calli, callback, d));
    }

    /**
     * 获取项目照片数据
     */
    public static void getProject(Context context, NovaCallback callback, int calli) {
        Map<String, Object> map = getParams(context);
        getNovate(context).rxPost(Contants.ProjectProgressOnLine, map, new Callback(calli, callback, d));
    }

    //----------------new----------------//
}
